import React, { Component } from 'react'

export default class Count extends Component {

  state = {
    count: 0
  }

  // 创建 Ref 容器
  myRef = React.createRef()

  // 加法回调函数
  onAdd = () => {
    const {value} = this.myRef.current
    const {count} = this.state
    // 计算新的状态值
    const newCount = count + parseInt(value)
    // 更新状态
    this.setState({
      count: newCount
    })
    console.log('onAdd-Ref', value, 'originState', count, 'sum', newCount)
  }

  // 减法回调函数
  onSubtract = () => {
    const {value} = this.myRef.current
    const {count} = this.state
    // 计算新的状态值
    const newCount = count - parseInt(value)
    // 更新状态
    this.setState({
      count: newCount
    })
  }

  // 奇数再加 回调函数
  onAddOdd = () => {
    const {value} = this.myRef.current
    const {count} = this.state
    // 计算新的状态值
    const newCount = count + parseInt(value)
    // 判断是否为奇数
    if(count % 2 !== 0){
      // 更新状态
      this.setState({
        count: newCount
      })
    }else{
      return console.log("当前求和为：偶数")
    }
  }

  // 异步加 回调函数
  onAddAsync = () => {
    const {value} = this.myRef.current
    const {count} = this.state
    // 计算新的状态值
    const newCount = count + parseInt(value)
    // 模拟异步操作
    setTimeout(() => {
      // 更新状态
      this.setState({
        count: newCount
      })
    }, 500)
  }

  render() {
    return (
      <div>
        <h1>当前求和为: {this.state.count}</h1>
        <select ref={this.myRef} style={{ margin: '10px', padding:'10px' }}>
          <option value="1">1</option>
          <option value="2">2</option>
          <option value="3">3</option>
        </select>&nbsp;
        <button 
          style={{ padding:'10px' }}
          onClick={this.onAdd}
        >+
        </button>&nbsp;
        <button 
          style={{ padding:'10px' }}
          onClick={this.onSubtract}
        >-
        </button>&nbsp;
        <button 
          style={{ padding:'10px' }}
          onClick={this.onAddOdd}
        >当前求和为奇数加
        </button>&nbsp;
        <button 
          style={{ padding:'10px' }}
          onClick={this.onAddAsync}
        >异步加
        </button>&nbsp;
      </div>
    )
  }
}
